<?php
/**
 * @author Evica Ilieva
 * @date 2012-06-29
 */
class CrossRefApiImplDAO implements RepositoryDAO{
	/**
	 * Get Document Object by doi
	 *
	 * @param String $doi
	 */
	public function searchByDoi($doi){
		
			
		$request_url = str_replace('[DOI]', $doi, RepositoryConnectionProperty::$_url);
		RepositoryConnectionProperty::$_url = $request_url;

		//Connect to the Repository
		$conn = new RepositoryConnection();

		//The connection returns an XML object
		$xml=$conn->getConnection();
			
		//Create empty objects for Document, Metadata and File
		$document = new Document();
		$metadata = new Metadata();
		$file = new File();
		$keywords = array();
		$resolved = false;
		if(!isset($xml->head->title)) {
			
				$record = $xml->query_result->body->query;
		
				foreach ($record->attributes() as $a => $b) {
		
					if ($a == 'status' && $b == 'resolved') {
						$resolved = true;
						break;
					}
				}
		}	
		
			if ($resolved) {
				$metadata->setDoi($doi);
				$metadata->setSecondaryTitle((string)$record->journal_title);
				$metadata->setYear($record->year);
				$metadata->setYear($metadata->getYear().'-01-01');
				$metadata->setVolume((string)$record->volume);
				$metadata->setIssue((string)$record->issue);
				$metadata->setPages($record->first_page);
				$last_page = $record->last_page;
				if (!empty($last_page)) 
				{
					$metadata->setPages($metadata->getPages()."-".$last_page);
				}
				$metadata->setTitle((string)$record->article_title);
				$metadata->setTitleAscii(utf8_deaccent((string)$record->article_title));
			
				foreach ($record->contributors->contributor as $contributor) {
			
					$authors1 = $contributor->surname;
					$authors2 = $contributor->given_name;
					$authors[] = $authors1.' '.$authors2;
				}
				$metadata->setAuthors(join(", ", $authors));
				$metadata->setAutorsAscii(utf8_deaccent((string)join(", ", $authors)));
				
			}
			$document->setMetadata($metadata);
			$document->setFile($file);
		
			return $document;
		}
		
		/**
		 * Get Document Object by uid
		 * @param String $uid
		 */
		public function searchByUid($uid){}
		
		public function findDoiByISSN($issn, $title){}
		
		public function searchByTitle($title){}
	}